package com.linzp.bishe.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.linzp.bishe.common.Constants;
import com.linzp.bishe.common.Result;
import com.linzp.bishe.controller.exception.ServiceException;
import com.linzp.bishe.entity.Accounts;
import com.linzp.bishe.entity.AchievementTransformation;
import com.linzp.bishe.entity.Participants;
import com.linzp.bishe.excel.AchievementTransformationExcel;
import com.linzp.bishe.excel.AchievementTransformationExcelListener;
import com.linzp.bishe.model.AchievementTransformationModel;
import com.linzp.bishe.model.StatusModel;
import com.linzp.bishe.service.*;
import com.linzp.bishe.utils.TableName;
import com.linzp.bishe.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 林泽鹏
 * @since 2021-11-01
 */
@RestController
@RequestMapping("/achievementTransformation")
@Transactional
public class AchievementTransformationController {
	@Autowired
	private AchievementTransformationService achievementTransformationService;

	@Autowired
	private ParticipantsService participantsService;

	@Autowired
	private AccountsService accountsService;

	@Autowired
	private UsersService usersService;

	@Autowired
	private SaveExcelData saveExcelData;

	/**
	 * @Description 普通用户通过ID获得数据
	 * @Param [httpServletRequest, current, page, searchContractName, searchAchievementName, searchStatus]
	 * @return com.linzp.bishe.common.Result
	 */
	@GetMapping("")
	public Result getAchievementTransformation(HttpServletRequest httpServletRequest, Integer current,
	                                   Integer page,String searchContractName,String searchAchievementName, String searchStatus){
		Accounts account = accountsService.checkAccountStatus(httpServletRequest);
		Result success = Result.success();
		Integer id = usersService.getByAccountIDUserID(account.getId()).getId();
		achievementTransformationService.getByIdAllAchievementTransformation(success,id,current,page,searchContractName,searchAchievementName,searchStatus);
		return success;
	}

	/**
	 * @Description 管理员获得数据
	 * @Param [httpServletRequest, current, page, searchContractName, searchAchievementName, searchStatus]
	 * @return com.linzp.bishe.common.Result
	 */
	@GetMapping("/admin")
	public Result getAdminAchievementTransformation(HttpServletRequest httpServletRequest, Integer current,
	                                           Integer page,String searchContractName,String searchAchievementName, String searchStatus){
		accountsService.checkAccountIsAdmin(httpServletRequest);
		Result success = Result.success();
		achievementTransformationService.getByIdAllAchievementTransformation(success,null,current,page,searchContractName,searchAchievementName,searchStatus);
		return success;
	}

	/**
	 * @Description 增加消息的时候用一个缓存先存放着防止网络中断或者不想要产生垃圾
	 * @Param [file]
	 * @return com.linzp.bishe.common.Result
	 */
	@PostMapping("/fileCache")
	public Result addSuportingMaterialsCache(@RequestParam("file") MultipartFile file){
		Result success = Result.success();
		success.put("saveName",achievementTransformationService.saveMultipartFile(file));
		return success;
	}

	/**
	 * @Description 更新文件
	 * @Param [file, fileName, id]
	 * @return com.linzp.bishe.common.Result
	 */
	@PostMapping("/upFile")
	public Result upSuportingMaterials(@RequestParam("file") MultipartFile file,String fileName,Integer id){
		Result success = Result.success();
		boolean check = true;
		String multipartFile;
		//如果没有文件，那么就新建然后保存，如果有那么就更改，然后如果文件后缀名改了
		// 例如.jpg变成了.word那么数据库的名字也需要更改
		if ( fileName == null || fileName.isEmpty()){
			multipartFile= achievementTransformationService.saveMultipartFile(file);
			achievementTransformationService.saveCacheToFile(multipartFile);
		}
		else {
			multipartFile=achievementTransformationService.updateMultipartFile(file,fileName);
			if (multipartFile.equals(fileName)){
				check = false;
			}
		}
		if(check){
			UpdateWrapper<AchievementTransformation> update = new UpdateWrapper<>();
			update.eq("id",id);
			update.set("supporting_material",multipartFile);
			achievementTransformationService.update(update);
		}
		return success;
	}

	/**
	 * @Description 普通用户添加信息
	 * @Param [httpServletRequest, achievementTransformationModel]
	 * @return com.linzp.bishe.common.Result
	 */
	@PostMapping("")
	public Result addAchievementTransformation(HttpServletRequest httpServletRequest,@RequestBody AchievementTransformationModel achievementTransformationModel){
		Accounts account = accountsService.checkAccountStatus(httpServletRequest);

		if (achievementTransformationService.cheakRepeat(achievementTransformationModel.getContractName())) throw new ServiceException("合同已存在,如需添加请联系管理员",null);

		Result success = Result.success();
		AchievementTransformation transformation = achievementTransformationModel.getAchievementTransformation();
		transformation.setStatus(Constants.NOTSUBMIT);
		transformation.setUserId(usersService.getByAccountIDUserID(account.getId()).getId());
		if (transformation.getSupportingMaterial()!=null & !transformation.getSupportingMaterial().isEmpty()){
			achievementTransformationService.saveCacheToFile(transformation.getSupportingMaterial());
		}
		achievementTransformationService.save(transformation);
		participantsService.saveListOfParticipants(achievementTransformationModel.getParticipants(),transformation.getId(), TableName.ACHIEVEMENT);
		return success;
	}

	/**
	 * @Description 修改信息
	 * @Param [achievementTransformationModel]
	 * @return com.linzp.bishe.common.Result
	 */
	@PutMapping("")
	public Result upAchievementTransformation(@RequestBody AchievementTransformationModel achievementTransformationModel){
		Result success = Result.success();
		AchievementTransformation transformation = achievementTransformationModel.getAchievementTransformation();
		achievementTransformationService.updateById(transformation);
		List<Participants> list = achievementTransformationModel.getParticipants();
		participantsService.dealParticipants(list,TableName.ACHIEVEMENT,transformation.getId());
		return success;
	}

	/**
	 * @Description 通过ID删除信息
	 * @Param [achievementTransformationModel]
	 * @return com.linzp.bishe.common.Result
	 */
	@DeleteMapping("")
	public Result deleteAchievementTransformation(@RequestBody AchievementTransformationModel achievementTransformationModel){
		Result success = Result.success();
		achievementTransformationService.deleteAchievementTransformation(achievementTransformationModel);
		return success;
	}

	@PutMapping("/status")
	public Result dealStatus(@RequestBody StatusModel statusModel){
		achievementTransformationService.dealStatus(statusModel.getId(),statusModel.getStatus());
		return Result.success();
	}

	@PostMapping("/addExcel")
	public Result addExcel(HttpServletRequest httpServletRequest,@RequestParam("file") MultipartFile file){
		if(file.isEmpty()){
			throw new ServiceException("没有文件",null);
		}
		if(!Constants.EXCEL.equals(file.getContentType())){
			throw new ServiceException("注意文件后缀为.xlsx",null);
		}
		Result success = Result.success();
		Accounts account = accountsService.checkAccountStatus(httpServletRequest);
		ThreadLocalUtils.localVar.set(account.getId().toString());
		try {
			EasyExcel.read(file.getInputStream(), AchievementTransformationExcel.class,new AchievementTransformationExcelListener(saveExcelData)).sheet().doRead();
		} catch (IOException e) {
			throw new ServiceException("注意导入指定模板文件",null);
		}

		return success;
	}
}
